<?php
/**
 * 夏日葵电商系统
 * http://www.xiarikui.com
 */
namespace Admin\Controller;
use Admin\Model\GoodsModel;
use Think\AjaxPage;
use Think\Page;
class GoodsController extends BaseController {
    /**
     *  商品分类列表
     */
    public function categoryList() {
        $cat_list = $this->getCate('goods_cat');
        $this->assign('cat_list', $cat_list);
        $this->display();
    }
    /**
     * 添加修改商品分类
     * 手动拷贝分类正则 ([\u4e00-\u9fa5/\w]+)  ('393','$1'), 
     */
    public function addEditCategory() {
        $mod = D('goods_cat');
        if(IS_POST){
            $p_data = I('post.');
            if(!$p_data['name']){
                $this->error('分类名称不能为空');
            }
            if(!$p_data['en_name']){
                $this->error('英文名称不能为空');
            }
            if($p_data['act']=='add'){
                $p_data['add_time'] = time();
                $result = $mod->add($p_data);
                if($result){
                    $this->success('添加成功',U('Admin/Goods/categoryList'));
                }else{
                    $this->error('添加失败');
                }
            }else{
                $p_data['up_time'] = time();
                $result = $mod->where(array('id'=>$p_data['id']))->save($p_data);
                if($result){
                    $this->success('编辑成功',U('Admin/Goods/categoryList'));
                }else{
                    $this->error('编辑失败');
                }
            }
        }else{
            $id = I('id')?I('id'):'';
            if($id){
                $act = 'edit';
            }else{
                $act = 'add';
            }
            $this->assign('act',$act);
            $info = $mod->where(array('id'=>$id))->find();
            $this->assign('goods_cat_info',$info);
            $cat_list = $mod->where(array('cat_id'=>0))->field('id,name')->select();
            $this->assign('cat_list',$cat_list);
            $this->display('_category');
        }
    }
    /**
     * 删除分类
     */
    public function delgoodsCat() {
        $goodsCat = M("goodsCat");
        $count = $goodsCat->where("cat_id = {$_GET['id']}")->count("id");
        $count > 0 && $this->error('该分类下还有分类不得删除!', U('Admin/Goods/categoryList'));
        $goods_count = M('Goods')->where("cat_id = {$_GET['id']}")->count('1');
        $goods_count > 0 && $this->error('该分类下有商品不得删除!', U('Admin/Goods/categoryList'));
        $goodsCat->where("id = {$_GET['id']}")->delete();
        $this->success("操作成功!!!", U('Admin/Goods/categoryList'));
    }
    /**
     *  商品列表
     */
    public function goodsList() {
        $cate = $this->getCate('goods_cat');
        $str = '';
        foreach($cate as $item => $value) {
            switch ($value['level']) {
                case 1:
                    $cate[$item]['name'] = '|-' . $value['name'];
                    $cate[$item]['en_name'] = '|-' . $value['en_name'];
                    break;
                case 2:
                    $cate[$item]['name'] = $str . '|--' . $value['name'];
                    $cate[$item]['en_name'] = $str . '|--' . $value['en_name'];
                    break;
            }
        }
        $this->assign('categoryList', $cate);
        $this->display();
    }
    /**
     *  商品列表
     */
    public function ajaxGoodsList() {
        $where = ' 1 = 1 ';
        $cate_mod = D('goods_cat');
        I('intro') && $where = "$where and " . I('intro') . " = 1";
        $cat_id = I('cat_id');
        // 关键词搜索               
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if ($key_word) {
            $where = "$where and (goods_name like '%$key_word%' or goods_sn like '%$key_word%')";
        }
        if ($cat_id > 0) {
            $grandson_ids = getGoodsSubCat($cat_id);
            $where .= " and cat_id in(" . implode(',', $grandson_ids) . ") "; // 初始化搜索条件
        }
        $model = M('Goods');
        $count = $model->where($where)->count();
        $Page = new AjaxPage($count, 10);
        $show = $Page->show();
        $order_str = "add_time desc";
        $goodsList = $model->where($where)->order($order_str)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        foreach((array)$goodsList as $k=>$v){
            $one_cat = $cate_mod->where(array('id'=>$v['cat_id']))->getField('name');
            $two_cat = $cate_mod->where(array('id'=>$v['second_cat_id']))->getField('name');
            $goodsList[$k]['goods_cat'] = $one_cat.($two_cat?'->'.$two_cat:'');
        }
        $catList = $cate_mod->select();
        $catList = convert_arr_key($catList, 'id');
        $this->assign('catList', $catList);
        $this->assign('goodsList', $goodsList);
        $this->assign('page', $show);
        $this->display();
    }
    /**
     * 添加修改商品
     */
    public function addEditGoods() {
        $id = I('id')?I('id'):'';
        if($id){
            $goodsImg = M('goods_img')->where(array('goods_id'=>$id))->select();
            $this->assign('goodsImg', $goodsImg);
            $spec_list = M('goods_spec')->where(array('goods_id'=>$id))->select();
            $this->assign('spec_list', $spec_list);
            $act = 'edit';
        }else{
            $act = 'add';
        }
        $this->assign('act',$act);
        $cat_list = M('goods_cat')->where(array('cat_id'=>0))->select();
        $this->assign('cat_list', $cat_list);
        $goods_list = M('goods')->where(array('id'=>$id))->find();
        $this->assign('goodsInfo', $goods_list);
        $second_cat_list = M('goods_cat')->where(array('cat_id'=>$goods_list['cat_id']))->select();
        $this->assign('second_cat_list', $second_cat_list);
        $this->display('_goods');
    }
    public function getCategory(){
        $id = I('parent_id')?I('parent_id'):'';
        $mod = M('goods_cat');
        $cat_list = $mod->where(array('cat_id'=>$id))->select();
        foreach((array)$cat_list as $k=>$v){
            $html .= '<option value="'.$v['id'].'">'.$v['name'].'</option>';
        }
        echo $html;
    }
    /**
     * 商品类型  用于设置商品的属性
     */
    public function goodsTypeList() {
        $model = M("GoodsType");
        $count = $model->count();
        $Page = new Page($count, 100);
        $show = $Page->show();
        $goodsTypeList = $model->order("id desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('show', $show);
        $this->assign('goodsTypeList', $goodsTypeList);
        $this->display('goodsTypeList');
    }
    public function addEditGoodsForm(){
        $mod = M('goods');
        if(IS_POST){
            $data = I('post.');
            if($data['act']=='add'){
                $data['add_time'] = time();
                if($_FILES['thumb']['name']){
                    $data['thumb'] = '/Public/upload/goods/'.$this->_uploadOne('thumb',$user_id);
                }
                $result = $mod->add($data);
                if($result){
                    $data['goods_img'] = array_filter($data['goods_img']);
                    $goods_img_mod = M('goods_img');
                    foreach((array)$data['goods_img'] as $k=>$v){
                        $check = $goods_img_mod->where(array('images'=>$v))->count();
                        if(!$check){
                            $goods_img_mod->add(array('goods_id'=>$result,'images'=>$v));
                        }
                    }
                    $spec_mod = M('goods_spec');
                    $store_spec_mod = M('goods_store_spec');
                    $store = M('business')->field('id')->select();
                    foreach((array)$data['spec_id'] as $k=>$v){
                        $spec['goods_id'] = $data['id'];
                        $spec['spec_name'] = $data['spec_name'][$k];
                        $spec['spec_price'] = $data['spec_price'][$k];
                        $spec['spec_mk_price'] = $data['spec_mk_price'][$k];
                        $spec_id = $spec_mod->add($spec);
                        foreach((array)$store as $kk=>$vv){
                            $store_spec_mod->add(array('store_id'=>$vv['id'],'spec_name'=>$spec['spec_name'],'spec_id'=>$spec_id,'goods_id'=>$result,'spec_price'=>$spec['spec_price'],'spec_mk_price'=>$spec['spec_mk_price']));
                        }
                    }
                    $this->success('添加成功',U('Admin/Goods/goodsList'));
                }else{
                    $this->error('添加失败');
                }
            }else{
                $data['up_time'] = time();
                if($_FILES['thumb']['name']){
                    $data['thumb'] = '/Public/upload/goods/'.$this->_uploadOne('thumb');
                }
                $result = $mod->where(array('id'=>$data['id']))->save($data);
                if($result){
                    $data['goods_img'] = array_filter($data['goods_img']);
                    $goods_img_mod = M('goods_img');
                    foreach((array)$data['goods_img'] as $k=>$v){
                        $check = $goods_img_mod->where(array('images'=>$v))->count();
                        if(!$check){
                            $goods_img_mod->add(array('goods_id'=>$data['id'],'images'=>$v));
                        }
                    }
                    $spec_mod = M('goods_spec');
                    $store_spec_mod = M('goods_store_spec');
                    $store = M('business')->field('id')->select();
                    foreach((array)$data['spec_id'] as $k=>$v){
                        $spec['goods_id'] = $data['id'];
                        $spec['spec_name'] = $data['spec_name'][$k];
                        $spec['spec_price'] = $data['spec_price'][$k];
                        $spec['spec_mk_price'] = $data['spec_mk_price'][$k];
                        if($v>0){
                            if($spec['spec_name'] && $spec['spec_price']){
                                $spec_mod->where(array('id'=>$v))->save($spec);
                            }else{
                                $spec_mod->where(array('id'=>$v))->delete();
                                $store_spec_mod->where(array('spec_id'=>$v))->delete();
                            }
                        }else{
                            if($spec['spec_name'] && $spec['spec_price']) {
                                $spec_id = $spec_mod->add($spec);
                                foreach((array)$store as $kk=>$vv){
                                    $store_spec_mod->add(array('store_id'=>$vv['id'],'spec_name'=>$spec['spec_name'],'spec_id'=>$spec_id,'goods_id'=>$data['id'],'spec_price'=>$spec['spec_price'],'spec_mk_price'=>$spec['spec_mk_price']));
                                }
                            }
                        }
                    }
                    $this->success('编辑成功',U('Admin/Goods/goodsList'));
                }else{
                    $this->error('编辑失败');
                }
            }
        }
    }
    /**
     * 删除商品
     */
    public function delGoods() {
        $goods_id = $_GET['id'];
        $error = '';
        // 判断此商品是否有订单
        $c1 = M('OrderGoods')->where("goods_id = $goods_id")->count('1');
        $c1 && $error .= '此商品有订单,不得删除! <br/>';
        // 商品团购
        $c1 = M('goods_groupon')->where("goods_id = $goods_id")->count('1');
        $c1 && $error .= '此商品有团购,不得删除! <br/>';
        // 商品退货记录
        $c1 = M('order_return')->where("goods_id = $goods_id")->count('1');
        $c1 && $error .= '此商品有退货记录,不得删除! <br/>';
        if ($error) {
            $return_arr = array('status' => -1, 'msg' => $error, 'data' => '',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);        
            $this->ajaxReturn(json_encode($return_arr));
        }
        // 删除此商品        
        M("Goods")->where('goods_id =' . $goods_id)->delete();  //商品表
        M("cart")->where('goods_id =' . $goods_id)->delete();  // 购物车
        M("comment")->where('goods_id =' . $goods_id)->delete();  //商品评论
        M("goods_consult")->where('goods_id =' . $goods_id)->delete();  //商品咨询
        M("goods_img")->where('goods_id =' . $goods_id)->delete();  //商品相册
        M("goods_stock")->where('goods_id =' . $goods_id)->delete();  //商品规格
        M("spec_img")->where('goods_id =' . $goods_id)->delete();  //商品规格图片
        M("goods_to_attr")->where('goods_id =' . $goods_id)->delete();  //商品属性     
        M("goods_collect")->where('goods_id =' . $goods_id)->delete();  //商品收藏          
        $return_arr = array('status' => 1, 'msg' => '操作成功', 'data' => '',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);        
        $this->ajaxReturn(json_encode($return_arr));
    }

    /**
     * 初始化编辑器链接     
     * 本编辑器参考 
     */
    private function initEditor() {
        $this->assign("URL_upload", U('Admin/Ueditor/imageUp', array('savepath' => 'goods'))); // 图片上传目录
        $this->assign("URL_imageUp", U('Admin/Ueditor/imageUp', array('savepath' => 'article'))); //  不知道啥图片
        $this->assign("URL_fileUp", U('Admin/Ueditor/fileUp', array('savepath' => 'article'))); // 文件上传s
        $this->assign("URL_scrawlUp", U('Admin/Ueditor/scrawlUp', array('savepath' => 'article')));  //  图片流
        $this->assign("URL_getRemoteImage", U('Admin/Ueditor/getRemoteImage', array('savepath' => 'article'))); // 远程图片管理
        $this->assign("URL_imageManager", U('Admin/Ueditor/imageManager', array('savepath' => 'article'))); // 图片管理        
        $this->assign("URL_getMovie", U('Admin/Ueditor/getMovie', array('savepath' => 'article'))); // 视频上传
        $this->assign("URL_Home", "");
    }
    /**
     * 动态获取商品规格选择框 根据不同的数据返回不同的选择框
     */
    public function ajaxGetSpecSelect() {
        $goods_id = $_GET['goods_id'] ? $_GET['goods_id'] : 0;
        $GoodsModel = new GoodsModel();
        //$_GET['spec_type'] =  13;
        $specList = D('Spec')->where("type_id = " . $_GET['spec_type'])->order('`order` desc')->select();
        foreach ($specList as $k => $v) {
            $specList[$k]['spec_item'] = D('SpecItem')->where("spec_id = " . $v['id'])->order('id')->getField('id,item');
        }
        $items_id = M('GoodsStock')->where('goods_id = ' . $goods_id)->getField("GROUP_CONCAT(`key` SEPARATOR '_') AS items_id");
        $items_ids = explode('_', $items_id);
        if ($goods_id) {
            $specImageList = M('SpecImg')->where("goods_id = $goods_id")->getField('spec_img_id,src');
        }
        $this->assign('specImageList', $specImageList);
        $this->assign('items_ids', $items_ids);
        $this->assign('specList', $specList);
        $this->display('ajax_spec_select');
    }
    /**
     * 动态获取商品规格输入框 根据不同的数据返回不同的输入框
     */
    public function ajaxGetSpecInput() {
        $GoodsModel = new GoodsModel();
        $goods_id = $_REQUEST['goods_id'] ? $_REQUEST['goods_id'] : 0;
        $str = $GoodsModel->getSpecInput($goods_id, $_POST['spec_arr']);
        exit($str);
    }
    /**
     * 删除商品相册图
     */
    public function delGoodsImg() {
        $path = I('filename', '');
        $result = M('goods_img')->where("images = '$path'")->delete();
        if($result){
            unlink($path);
        }
    }
    //商品评论
    function comment(){
        $mod = M('orders_comment');
        $where = '1=1';
        $keywords = trim(I('keywords'));
        $keywords && $where.=" and (a.order_sn like '%$keywords%' or c.goods_name like '%$keywords%')";
        $p = empty($_REQUEST['p']) ? 1 : $_REQUEST['p'];
        $size = 20;
        $count = $mod->alias('as a')->join('left join '.C('DB_PREFIX').'goods as c on c.id=a.goods_id')->where($where)->count();
        $pager = new \Think\Page($count, $size);
        $page = $pager->show();
        $comment_list = $mod->alias('as a')->where($where)
            ->join('left join '.C('DB_PREFIX').'goods as c on c.id=a.goods_id')
            ->join('left join '.C('DB_PREFIX').'goods_store_spec as b on b.id=a.spec_id')
            ->join('left join '.C('DB_PREFIX').'users as d on d.id=a.user_id')
            ->join('left join '.C('DB_PREFIX').'business as e on e.id=a.store_id')
            ->order('a.add_time desc')
            ->page("$p,$size")
            ->field('a.order_sn,c.goods_name,b.spec_name,e.store_name,d.user_name,a.star,a.contents,a.images,a.add_time')
            ->select();
        foreach((array)$comment_list as $k=>$v){
            $v['images'] && $comment_list[$k]['images'] = explode(',',$v['images']);
        }
        $this->assign('comment_list',$comment_list);
        $this->assign('page', $page);
        $this->assign('keywords', $keywords);
        $this->display();
    }
}
